package org.benjamin.wechat.interceptor;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.benjamin.wechat.domain.Menu;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MenuLoadInterceptor extends HandlerInterceptorAdapter {
	
	private Logger logger = LogManager.getLogger();

	private List<Menu> extendMenu = new ArrayList<>();

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		if(modelAndView != null){
			Object temp = request.getAttribute("menus");
			if(temp == null) {
				logger.debug("加载菜单数据");
				ClassPathResource classPathResource = new ClassPathResource("menus.json");
				ObjectMapper objectMapper = new ObjectMapper();
				List<Menu> menus = extracted(classPathResource, objectMapper);
				modelAndView.addObject("menus",menus);
			}
			modelAndView.addObject("extendMenu",extendMenu);
		}
	}

	@SuppressWarnings("unchecked")
	private List<Menu> extracted(ClassPathResource classPathResource, ObjectMapper objectMapper)
			throws IOException, JsonParseException, JsonMappingException {
		return objectMapper.readValue(classPathResource.getFile(), List.class);
	}
	
	
	

	
}
